class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k)
    {
        unordered_map<int, int> cnt;

        for (auto e : nums) cnt[e]++;

        multimap<int, int> result;

        for (auto [x, y] : cnt)
        {
            result.insert({ y,x });
        }

        vector<int> ret;

        auto it = result.end();

        while (k--)
        {
            it--;
            ret.push_back(it->second);
        }

        return ret;
    }
};